package com.yzt.sys.service.impl;

import com.yzt.sys.entity.Permission;
import com.yzt.sys.mapper.PermissionMapper;
import com.yzt.sys.service.IPermissionService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yzt.base.dto.ZTreeDTO;
import com.yzt.base.kit.BaseResult;
import com.yzt.base.service.impl.BaseServiceImpl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 权限表 服务实现类
 * </p>
 *
 * @author Y
 * @since 2020-12-02
 */
@Service
@CacheConfig(cacheNames = "default",keyGenerator = "keyGenerator")
public class PermissionServiceImpl extends BaseServiceImpl<PermissionMapper, Permission> implements IPermissionService {

	private static int MAX_OPEN_LEVEL = 2;

	@Override
	@Cacheable
	public BaseResult<List<ZTreeDTO>> getPermissionZTreeData() {
		List<Permission> list = this.list(Wrappers.lambdaQuery(Permission.class).isNull(Permission::getParentId));
		List<ZTreeDTO> ztreeList = new ArrayList<>();
		int openLevel = 0;
		for (Permission p : list) {
			ZTreeDTO dto = new ZTreeDTO();
			dto.setId(p.getId());
			dto.setName(p.getName());
			if (openLevel < MAX_OPEN_LEVEL)
				dto.setOpen(true);
			getPermissionZTreeData(dto, openLevel + 1);
			ztreeList.add(dto);
		}
		return BaseResult.okData(ztreeList);
	}

	public void getPermissionZTreeData(ZTreeDTO dto, int openLevel) {
		List<Permission> list = this.list(Wrappers.lambdaQuery(Permission.class).eq(Permission::getParentId, dto.getId()));
		List<ZTreeDTO> ztreeList = new ArrayList<>();
		for (Permission p : list) {
			ZTreeDTO cdto = new ZTreeDTO();
			cdto.setId(p.getId());
			cdto.setName(p.getName());
			if (openLevel < MAX_OPEN_LEVEL)
				cdto.setOpen(true);
			getPermissionZTreeData(cdto, openLevel + 1);
			ztreeList.add(cdto);
		}
		dto.setChildren(ztreeList);
	}
}
